%This MATLAB script was originally used for the paper 
%"Evaluation of Pre-reconstruction Interpolation Methods for Iterative Reconstruction of Radial k-Space Data": 
%http://onlinelibrary.wiley.com/doi/10.1002/mp.12357/abstract

%The source for this script is "https://github.com/edibella/Reconstruction/tree/master/%2BGROG" 

function kSpace_cart_out = interp(kSpace_radial,G,Weighting,GPU)

% sx = G.siz(1);
% nor = G.siz(2);
% nof = G.siz(3);
% nc = G.siz(4);
[sx,nor,nof,nc]=size(kSpace_radial);

kSpace_radial = reshape(kSpace_radial,[sx*nor*nof,1,1,nc]);

if GPU
    kSpace_radial = gpuArray(kSpace_radial);
    kSpace_cart = zeros([(sx+2)*(sx+2) nof nc],'like',kSpace_radial);
else
    kSpace_cart = zeros([(sx+2)*(sx+2) nof nc]);
end

G_all = G.Dict_r2c(G.indx_r2c,:,:);
if GPU
    G_all = gpuArray(G_all);
end
G_all = reshape(G_all,[sx*nor*nof,1,nc,nc]);

k_target = bsxfun(@times,G_all,kSpace_radial);
k_target = sum(k_target,4);

k_target = reshape(k_target,[sx*nor,nof,1,nc]);

% if Weighting
%     k_target = bsxfun(@times,k_target,G.weight1);
% end

k_target = permute(k_target,[1 3 4 2]);
k_target = reshape(k_target,[sx*nor,nc,nof]);

for i=1:nof
    kSpace_cart(:,i,:) = single(G.rad2cart{i}*double(k_target(:,:,i)));
end

if Weighting
%     G.weight=1./G.weight;
    kSpace_cart = bsxfun(@times,kSpace_cart,G.weight);
end
kSpace_cart = reshape(kSpace_cart,[sx+2 sx+2 nof nc]);
kSpace_cart_out = kSpace_cart(2:end-1,2:end-1,:,:);

